<template>
  <div class="main">
    <div class="cartApp">
      <div class="cartNavigation">
        <el-breadcrumb
          class="product-breadcrumb" separator=">">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item >购物车</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 购物车列表 -->
      <div class="cartList">
        <el-table
          :data="shoppingCartList"
          ref="shoppingCartRef"
          :span-method="arraySpanMethod"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <!-- 列表 -->
          <el-table-column prop="name" label="商品信息" width="400">
            <template v-slot="scope">
              <div class="shoppingInfo">
                <a :href="`#/product/${scope.row.id}`">
                  <img :src="scope.row.picture">
                </a>
                <div class="goods-name">
                  <div>{{ scope.row.name }}</div>
                  <!-- <el-popconfirm
                    confirm-button-text="OK"
                    placement="bottom-start"
                    trigger="click"
                    width="400px"
                  > -->
                  <el-popover
                    placement="bottom-start"
                    trigger="click"
                    width="400px"
                  >
                    <template #reference>
                      <div @click="onCartLayer(scope)">
                        {{ scope.row.attrsText }}
                        <el-icon><ArrowDownBold /></el-icon>
                      </div>
                    </template>
                    <div class="shopping-layer">
                      <shopping-group
                        :goods-details="scope.row.goodsSkuDetail" :row-data="rowData"
                        @layerUpdate="init"
                      />
                    </div>
                  </el-popover>
                  <!-- </el-popconfirm> -->
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价">
            <template v-slot="scope">
              <span>¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量">
            <template v-slot="scope">
              <el-input-number
                v-model="scope.row.count"
                :min="1"
                :max="scope.row.stock"
                @change="onChangeCount(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计">
            <template v-slot="scope">
              <span class="cart-shopping-sum">¥{{ (scope.row.count * scope.row.price).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作">
            <template v-slot="scope">
              <div class="cart-operation">移入收藏夹</div>
              <div class="cart-operation cart-del" @click="onDeleteShopping([scope.row.skuId])">删除</div>
              <div class="cart-operation">找相似</div>
            </template>
          </el-table-column>
          <!-- 购物车空状态 -->
          <template #empty>
            <div class="table-empty">
              <img src="" alt="notData" />
              <div>购物车内暂时没有商品</div>
              <div><button @click="toHome">继续逛逛</button></div>
            </div>
          </template>
        </el-table>
      </div>
      <div class="cart-settlement">
        <div class="left">
          <div>
            <el-checkbox
              v-model="isChecked"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
          </div>
          <div @click="delAllShopping">删除商品</div>
          <div>移入收藏夹</div>
          <div @click="delFailureShopping">清空失效商品</div>
        </div>
        <div class="right">
          <div class="no-btn">
            共{{ totalAmount.total }}件商品，已选择{{ totalAmount.check }}件，商品合计：
            <span class="price">¥{{ totalAmount.priceSum }}</span>
          </div>
          <div><button class="btn">下单结算</button></div>
        </div>
      </div>
      <!-- 猜你喜欢 -->
      <div class="like">
        <div class="goods-relevant">
          <div class="header">猜你喜欢</div>
          <div class="carousel" >
            <el-carousel
              indicator-position="outside"
              :autoplay="false"
              arrow="always"
              trigger="click"
            >
              <el-carousel-item v-for="item in goodsRelevant" :key="item.id">
                <div class="carousel-card">
                  <div v-for="sub in item" :key="sub.id" class="carousel-card-item" @click="onGoDetail(sub.id)">
                    <div>
                      <img :src="sub.picture" alt="">
                    </div>
                    <div class="carousel-card-name">{{ sub.name }}</div>
                    <div class="carousel-card-price">￥{{ sub.price }}</div>
                  </div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>

        </div>
      </div>
      <div class="emp"></div>
    </div>
  </div>
</template>

<script setup>
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ShoppingGroup from '../../components/ShoppingGroup/index.vue';

const router = useRouter();
const route = useRoute();
const store = useStore();
const shoppingCartRef = ref();
const goodsRelevant = ref([]);
// 选中商品的信息
const totalAmount = ref({
  total: 0,
  check: 0,
  priceSum: 0,
});
// 下面多选框设置是否横杠
const isIndeterminate = ref(false);
const isChecked = ref(false);

const shoppingCartList = ref([]);

async function init() {
  await store.dispatch('home/getAllShoppingCartList');
  const res = await computed(() => store.state.home.shoppingCartList);
  totalAmount.value.total = await res.value.reduce((p, v) => p + v.count, 0);
  // 商品同类推荐
  await store.dispatch('goods/updateGoodsRelevant', route.params.id);
  // 引用处理好的getters的同类推荐数据
  goodsRelevant.value = store.getters['goods/goodsRelevantGroup'];
  // isEffective false 失效商品
  // res.value = res.value.map((item) => ({
  //   ...item,
  //   isEffectiveUpdate: false,
  // }));
  let tempData = [];
  for (let i = 0; i < res.value.length; i++) {
    tempData.push({ ...res.value[i] });
  }
  // tempData = tempData.map((item) => ({
  //   ...item,
  //   isEffective: false,
  // }));

  const effective = tempData.filter((item) => item.isEffective);
  const invalid = tempData.filter((item) => !item.isEffective);
  if (invalid.length > 0) {
    tempData = effective;
    tempData.push({ name: '无效商品' });
    for (let i = 0; i < invalid.length; i++) {
      tempData.push(invalid[i]);
    }
  }
  res.value = tempData;

  shoppingCartList.value = tempData.map((item) => {
    return {
      ...item,
      goodsSkuDetail: {},
    };
  });
}
init();

// 表格合并
const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (columnIndex === 1) {
    if (row.name === '无效商品') {
      return [1, 6];
    }
  }
};

// 表格多选框状态改变时
const handleSelectionChange = (val) => {
  const checkList = shoppingCartRef.value?.getSelectionRows();
  if (checkList.length === 0) {
    isIndeterminate.value = false;
    isChecked.value = false;
  } else if (checkList.length === shoppingCartList.value.length) {
    isIndeterminate.value = false;
    isChecked.value = true;
  } else {
    isIndeterminate.value = true;
  }
  // 计算选中商品合计金额
  totalAmount.value.priceSum = checkList.map((item) => item.count * item.price).reduce((p, v) => p + v, 0);
  totalAmount.value.check = checkList.reduce((p, v) => p + v.count, 0);
};

// 第二个全选框
const handleCheckAllChange = () => {
  shoppingCartRef.value?.toggleAllSelection();
};

// 删除商品
function onDeleteShopping(ids) {
  ElMessageBox.confirm(
    '亲，您是否确认删除商品',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await store.dispatch('home/delShoppingCartList', { ids });
      const res = await computed(() => store.state.home.delShoppingCartMsg);
      if (res.value === '操作成功') {
        ElMessage({ message: '删除成功！' });
      } else {
        ElMessage({ type: 'error', message: '删除失败！' });
      }
      await init();
    })
    .catch(() => { });
}

// 删除选中商品
function delAllShopping() {
  const checkList = shoppingCartRef.value?.getSelectionRows();
  if (checkList.length === 0) {
    ElMessage({ type: 'error', message: '请选择需要删除的商品！' });
    return;
  }
  const ids = checkList.map((item) => item.skuId);
  onDeleteShopping(ids);
}

// 删除失效商品
function delFailureShopping() {
  const ids = [];
  onDeleteShopping(ids);
}

// 修改商品数量
async function onChangeCount(data) {
  await store.dispatch('home/updateShoppingCartNum', data);
  await init();
}

// 跳转到首页
function toHome() {
  router.push({
    path: '/',
  });
}

// 触发商品选择框
const goodsSkuDetail = ref([]);
const rowData = ref({});
async function onCartLayer(row) {
  goodsSkuDetail.value = [];
  await store.dispatch('goods/updateGoodsSkuDetail', row.row.skuId);
  const res = await computed(() => store.state.goods.goodsSkuDetail);
  res.value.specs = res.value.specs.map((s) => ({
    ...s,
    disabled: s.values.map(() => true),
  }));
  goodsSkuDetail.value = res.value;
  rowData.value = row.row;
  row.row.goodsSkuDetail = res.value;
}


</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: rgb(245, 245, 245);
  padding: 1px 0;
}
.cartApp {
  width: 1240px;
  margin: 0 auto;
}
.cartNavigation {
  padding-top: 20px;
  margin-bottom: 18px;
}
.shoppingInfo {
  display: flex;
  align-items: center;
  padding: 10px;
  box-sizing: border-box;
  img {
    height: 100px;
    width: 100px;
  }
  .goods-name{
    width: 280px;
    height: 62px;
    padding-left: 10px;
    position: relative;
    & div:first-child{
        width: 270px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #666;
      }
    & div:nth-child(2){
      display: inline-block;
      max-width: 230px;
      padding: 0 6px;
      border: 1px solid #ccc;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #999;
      margin-top: 6px;
    }
    .shopping-layer {
      position: absolute;
      top: 0;
      left: 0;
      height: 300px;
      padding: 10px;
      outline: 1px solid red;
    }
  }
}
.cart-shopping-sum {
  color: red;
  font-size: 16px;
}
.cart-operation {
  cursor: pointer;
}
.cart-del {
  color: #5cb79d;
}

.left {
  display: flex;
  float: left;
}
.right {
  display: flex;
  float: right;
}
.cart-settlement {
  height: 80px;
  box-sizing: border-box;
  //width: 1240px;
  //margin: 20px 0 auto;
  line-height: 80px;
  margin-top: 20px;
  padding: 0 30px;
  background-color: #fff;
  .left div, .right div{
    display: flex;
    margin-right: 20px;
    cursor: pointer;
  }
  .price {
    color: red;
    font-size: 18px;
  }
  .el-checkbox {
    color: #000;
    margin: auto;
  }
  .btn {
    width: 160px;
    height: 46px;
    margin: auto 0;
    background-color: rgb(39, 186, 155);
    border: 1px solid rgb(39, 186, 155);
    border-radius: 5px;
    cursor: pointer;
    color: #fff;
    font-size: 16px;
  }
  .no-btn {
    cursor: auto !important;
  }
}
.table-empty {
  padding: 150px 0;
  button {
    width: 180px;
    height: 50px;
    background-color: rgb(39, 186, 155);
    font-size: 16px;
    text-align: center;
    border: 1px solid rgb(39, 186, 155);
    border-radius: 4px;
    cursor: pointer;
    color: #fff;
  }
}
.like{
  margin-top: 20px;
  background: #fff;
  height: 460px;
  width: 1240px;
  .header{
    height: 80px;
    line-height: 80px;
    padding: 0 20px;
    font-size: 20px;
  }
  .goods-relevant{
    width: 1240px;
    height: 460px;
    margin-top: 20px;
    background: #fff;
    .header{
      height: 80px;
      line-height: 80px;
      padding: 0 20px;
      font-size: 20px;
    }
    .carousel{
      height: 380px;
      :deep(.el-icon){
        color: #ddd;
        font-size: 36px;
      }
      .carousel-card{
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 0 40px;

        .carousel-card-item{
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          width: 240px;
          height: 290px;
          cursor: pointer;
          img{
            width: 190px;
            height: 190px;
          }
          .carousel-card-name{
            width: 200px;
            box-sizing: border-box;
            padding-top: 16px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .carousel-card-price{
            box-sizing: border-box;
            padding-top: 16px;
            color: #cf4444;
          }
        }
      }
    }
  }
}
.emp{
  height: 20px;
}


</style>
